package com.quanyan.video.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.video.common.Sign;
import com.quanyan.video.entity.Bucket;
import com.quanyan.video.entity.Project;
import com.quanyan.video.repository.BucketRepository;
import com.quanyan.video.repository.ProjectRepository;
import com.quanyan.video.request.ReqBucket;
import com.quanyan.video.request.ReqVideo;
import com.quanyan.video.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Valid;
import java.util.Date;

/**
 * Created by wmb on 2016/6/27.
 */
@Service("videoService")
public class VideoServiceImpl implements VideoService{
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private BucketRepository bucketRepository;
    @Override
    @Valid
    public APIResponse<String> getSign(ReqVideo reqVideo) {
        String projectName="";
        if(StringUtil.isBlankOrNull(reqVideo.getProjectName())){
            projectName="默认项目";
        }else{
            projectName=reqVideo.getProjectName();
        }
        Project project=projectRepository.selectByName(projectName);
        bucketRepository.selectByProjectAndName(project.getId(),reqVideo.getBucketName());
        Long expired=getExpiredByDay(project.getExpired());
        //多次有效签名
        if(StringUtil.isBlankOrNull(reqVideo.getResourcePath())){
            String sign = Sign.appSign(project.getAppId(), project.getSecretId(), project.getSecretKey(), expired, reqVideo.getBucketName());
            return APIResponse.returnSuccess(sign);
        }else{
            //单次有效签名
            String sign = Sign.appSignOnce(project.getAppId(), project.getSecretId(), project.getSecretKey(), reqVideo.getResourcePath(), reqVideo.getBucketName());
            return APIResponse.returnSuccess(sign);
        }
    }

    @Override
    public APIResponse<Integer> addProject(Project project) {
        return APIResponse.returnSuccess(projectRepository.insertSelective(project) );
    }

    @Override
    @Valid
    public APIResponse<Integer> addBucket(ReqBucket reqBucket) {
        Project project=projectRepository.selectByName(reqBucket.getProjectName());
        Bucket bucket=new Bucket();
        bucket.setProjectId(project.getId());
        bucket.setName(reqBucket.getBucketName());
        bucket.setState((byte)1);
        return APIResponse.returnSuccess(bucketRepository.insertSelective(bucket));
    }

    private Long getExpiredByDay(Byte expired) {
        Date expiredDate=DateUtils.addNDay(new Date(), Integer.parseInt(expired.toString()));
        return expiredDate.getTime()/1000;
    }
}
